package org.kazuhiko.rpg.server.net;

import java.util.ArrayDeque;
import java.util.Queue;

import org.apache.mina.core.session.IoSession;
import org.kazuhiko.rpg.server.net.packet.Packet;

public abstract class Connectable
{
	protected final Queue<Packet> queuedPackets = new ArrayDeque<Packet>();
	
	protected State state = State.CONNECTED;
	
	protected void send( Packet packet, IoSession session )
	{
		synchronized( this )
		{
			final String name = packet.getDefinition().getName();
			final boolean unqueuedPacket = name.equals( "disconnect" ) || name.equals( "addEntity" );
			
			if( state == State.READY )
			{
				if( queuedPackets.size() > 0 )
				{
					for( Packet queuedPacket : queuedPackets )
					{
						//Send the packet
						session.write( queuedPacket );
					}
				}
			}
			else if( unqueuedPacket )
			{
				//we still send the packet :$
				session.write( packet );
			}
			else
			{
				queuedPackets.add( packet );
			}
		}
	}
}
